package com.kb.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.security.spec.KeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

final public class DesEncrypter {
	
	private static DesEncrypter desEncrypter = null;
	
	// Cipher object for encrypting.
	private Cipher ecipher = null;

	// Cipher object for decrypting.
	private Cipher dcipher = null;


	/**
	 * Gets the instance attribute of the DesEncrypter class
	 * 
	 * @return The instance value
	 */
	public static DesEncrypter getInstance() {
		// Note done statically because we don't know when PI_KEY is set realtive to object creation
		if (desEncrypter == null) {
			desEncrypter = new DesEncrypter(".-'/W2@cty#vw6&H");
		}
		return desEncrypter;
	}
	
	/**
	 * Construct the object by using a given password phrase.
	 * 
	 * @param passPhrase  Specifies a password phrase.
	 */
	private DesEncrypter(String passPhrase) {
		try {
			// Create the key
			KeySpec keySpec = new DESKeySpec(passPhrase.getBytes());
			SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

			ecipher = Cipher.getInstance("DES");
			dcipher = Cipher.getInstance("DES");

			// Create the ciphers
			ecipher.init(Cipher.ENCRYPT_MODE, key);
			dcipher.init(Cipher.DECRYPT_MODE, key);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Encrypt a string.
	 * 
	 * @param str
	 *            String to be encrypt.
	 * @return A encrpted string.
	 */
	public String encrypt(String str) {
		try {
			// Encode the string into bytes using utf-8
			byte[] utf8 = str.getBytes("UTF8");

			// Encrypt
			byte[] enc = ecipher.doFinal(utf8);

			// Encode bytes to base64 to get a string
			return new sun.misc.BASE64Encoder().encode(enc);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Decrypt a encrypted string.
	 * 
	 * @param str A encrypted string.
	 * @return The original string.
	 */
	public String decrypt(String str) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

			// Decrypt
			byte[] utf8 = dcipher.doFinal(dec);

			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}